/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import NetCommunicator.NetCommunicator;
import Signer.Signer;
import WASACommunicator.WASACommunicator;
import jWASA.*;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Set;
import java.util.TooManyListenersException;

/**
 *
 * @author gianmariospacagna
 */
public class RTMeasurements extends Thread {

    NetCommunicator netCommunicator;
    WASACommunicator wCommunicator;
    Set<Sensor> sensors;
    Boolean stop;
    Signer signer;
    int rate;

    public RTMeasurements(String port, Set<Sensor> sensors, int rate, Signer signer, InetAddress serverLocation, int serverPort) throws TooManyListenersException {
        this.netCommunicator = new NetCommunicator(serverLocation, serverPort);
        this.wCommunicator = new WASACommunicator(port);
        this.sensors = sensors;
        this.signer = signer;
        stop = true;
        this.rate=rate;

    }

    @Override
    public void start() {
        wCommunicator.activateStreamData(sensors, rate);
        ArrayList<Sample> samples;
        stop = false;

        while (!stop) {
            try {
                for (Sensor sensor : sensors) {
                    samples = wCommunicator.getSamples(sensor);
                    for (Sample s : samples) {
                        //System.out.println("RTM-> Sample: " + s.toString());
                        //SignedSample ss = signer.sign(s);
                        netCommunicator.sendData(s);
                    }
                }

                if (stop) {
                    wCommunicator.stopMeasurements();
                }
            } catch (Exception e) {
                //e.printStackTrace();

                System.err.println("RTM-> Error sending sample");
            }
        }
    }

    public void stopMonitoring() {

        stop = true;
    }
}
